package controller

import (
	"GoAdmin/common"
	"GoAdmin/models"
	"GoAdmin/utils"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"io/ioutil"
	"log"
	"math"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
	"xorm.io/builder"
)

var (
	Sex = map[string]string{"1": "男性", "2": "女性"}
)

const BaeUrl = "http://api.hahajishi.cn:80"

//const BaeUrl = "http://127.0.0.1:80"

func RecordList(c *gin.Context) {
	user, _ := common.GetCtxUser(c)
	filter := builder.NewCond()
	if user.Type == "0" || user.Type == "1" {
		//管理用户查询全部
	} else {
		if user.Province != "" {
			filter = filter.And(builder.Eq{"sl.province": user.Province})
		}
		if user.City != "" {
			filter = filter.And(builder.Eq{"sl.city": user.City})
		}
		if user.District != "" {
			filter = filter.And(builder.Eq{"sl.district": user.District})
		}
	}
	if user.Type == "3" {
		//同一个地区双代理
		filter = filter.And(builder.Eq{"sl.config": user.SchoolList})
	}
	if schoolId := c.PostForm("school_id"); schoolId != "" {
		filter = filter.And(builder.Eq{"ld.school_id": schoolId})
	}
	if name := c.PostForm("name"); name != "" {
		filter = filter.And(builder.Eq{"u.name": name})
	}
	if phone := c.PostForm("phone"); phone != "" {
		filter = filter.And(builder.Eq{"u.phone": phone})
	}
	if idNumber := c.PostForm("id_number"); idNumber != "" {
		filter = filter.And(builder.Eq{"u.id_number": idNumber})
	}
	if subject := c.PostForm("subject"); subject != "" {
		filter = filter.And(builder.Eq{"ld.subject": subject})
	}
	//return
	page, _ := strconv.Atoi(c.DefaultPostForm("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultPostForm("pageSize", "15"))
	offset := (page - 1) * pageSize

	count, list, _ := new(models.LearnRecord).GetRecordList(filter, pageSize, offset)
	for k, v := range list {
		list[k].Mileage = cast.ToFloat32(utils.Decimal(cast.ToFloat64(v.Mileage/10), "2"))
		if v.ApprovalStatus == "1" {
			list[k].Reason = "--"
		}
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "成功", "data": gin.H{"list": list, "count": count}})
	return
}

func RecordFailListTest(c *gin.Context) {
	filter := builder.NewCond()
	//log.Println(page, pageSize, offset)
	//查询当天内备案失败学时
	if c.PostForm("start_time") == "" {
		filter = filter.And(builder.Gte{"ld.start_time": time.Now().Format("2006-01-02") + " 00:00:00"})
	} else {
		filter = filter.And(builder.Gte{"ld.start_time": c.PostForm("start_time") + " 00:00:00"})
	}

	if c.PostForm("start_time") == "" {
		filter = filter.And(builder.Lte{"ld.start_time": time.Now().Format("2006-01-02") + " 23:59:59"})
	} else {
		filter = filter.And(builder.Lte{"ld.start_time": c.PostForm("end_time") + " 23:59:59"})
	}

	filter = filter.And(builder.Eq{"ld.approval_status": "2"})
	list, _ := new(models.LearnRecord).GetUnRecordListTest(filter)
	var dataMap []map[string]interface{}
	for _, v := range list {
		if v.Reason == "同一学员培训时段已存在" || v.Reason == "小于规定时长" || v.Reason == "课堂培训日志教练员编号不能为空！" || v.Reason == "请上传大小在10kb-1M范围内的图片" {

		} else {
			data := map[string]interface{}{
				"id":                v.Id,
				"approval_status":   v.ApprovalStatus,
				"car_number":        v.CarNumber,
				"coach_name":        v.CoachName,
				"course":            v.Course,
				"end_time":          v.EndTime,
				"id_number":         v.IdNumber,
				"lasting_minute":    v.LastingMinute,
				"mileage":           cast.ToFloat32(utils.Decimal(cast.ToFloat64(v.Mileage/10), "2")),
				"name":              v.Name,
				"name_short":        v.NameShort,
				"operation_status":  v.OperationStatus,
				"phone":             v.Phone,
				"plate_number":      v.PlateNumber,
				"reason":            v.Reason,
				"record_status":     v.RecordStatus,
				"start_time":        v.StartTime,
				"subject":           v.Subject,
				"title":             v.Title,
				"training_car_type": v.TrainingCarType,
			}
			dataMap = append(dataMap, data)
		}
		//log.Println(v.Name, v.Mileage)
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "成功", "data": gin.H{"list": dataMap, "count": len(dataMap)}})
	return

}

type trail struct {
	Latitude  float32
	Longitude float32
	ImageUrl  string
}

func RecordFailSurvey(c *gin.Context) {
	var (
		curMileage          float32
		curHours            int
		subjectTotalHours   int64
		subjectTotalMileage float64
		renKeTime           int64
		last                time.Time
		trailList           []trail
		coachLogin          string
		coachLogout         string
		coachLoginTime      time.Time
		coachLogoutTime     time.Time
		record              models.RecordSurvey
	)
	//获取参数
	valid := validation.Validation{}
	valid.Required(c.PostForm("id"), "id").Message("记录未找到")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}
	if record, _ = new(models.LearnRecord).Survey(c.PostForm("id")); record.Id == 0 {
		fmt.Println(record, "-----------------")
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "未找到该记录", "data": nil})
		return
	}
	subject := record.Subject
	trainCarInfo, _ := new(models.TrainCarinfo).GetTrainCarinfo(record.TrainingCarType)

	//大纲总学时
	hourMap := map[string]int64{
		"1": trainCarInfo.HoursSubject1,
		"2": trainCarInfo.HoursSubject2,
		"3": trainCarInfo.HoursSubject3,
		"4": trainCarInfo.HoursSubject4,
	}
	//大纲总里程
	mileageMap := map[string]int{
		"1": trainCarInfo.TotalmileageSubject1,
		"2": trainCarInfo.TotalmileageSubject2,
		"3": trainCarInfo.TotalmileageSubject3,
		"4": trainCarInfo.TotalmileageSubject4,
	}
	//查询 0<速度<5 ,速度=5, 速度>5 的记录数
	zero, _ := new(models.LearnRecordGnss).Zero(c.PostForm("id"))
	zeroFive, _ := new(models.LearnRecordGnss).ZeroFive(c.PostForm("id"))
	five, _ := new(models.LearnRecordGnss).Five(c.PostForm("id"))
	filter := builder.NewCond()
	filter = builder.Eq{"ld.subject": subject}.And(builder.Eq{"ld.student_id": record.StudentId}.And(builder.Lte{"ld.end_time": record.EndTime}))
	nums, lists, err := new(models.LearnRecord).GetSumMileageAndLastingMinute(filter)
	if err == nil && nums != false {
		if lists.Mileage != 0 {
			curMileage = lists.Mileage / 10.0
		} else {
			curMileage = 0.00
		}
		curHours = lists.LastingMinute
	}
	subjectTotalHours = hourMap[subject] * 45
	//log.Println("大纲学时：", subjectTotalHours)
	if subject == "2" || subject == "3" {
		renke, _ := new(models.LearnRecordGnss).Renke(c.PostForm("id"))
		last_minute, _ := strconv.ParseFloat(record.LastingMinute, 64)
		if float64(renke)/last_minute < 0.75 {
			renKeTime = int64(renke * 4 / 3)
		} else {
			renKeTime = renke
		}
		subjectTotalMileage = float64(mileageMap["2"] + mileageMap["3"])
	} else {
		if record.ApprovalStatus == "1" {
			lastMinute, _ := strconv.ParseFloat(record.LastingMinute, 64)
			renKeTime = int64(lastMinute)
		} else {
			renKeTime = 0
		}
		subjectTotalMileage = float64(0)
	}
	gnss, _ := new(models.LearnRecordGnss).GetGnss(c.PostForm("id"))
	file, _ := new(models.File).GetFileByLearnRecordId(c.PostForm("id"))
	for k, v := range gnss {
		for _, image := range file {
			if k == 0 {
				if image.AddTime.Before(v.Add_time) {
					gnss[k].Image = image.FileUrl
				} else {
					if image.AddTime.After(last) && image.AddTime.Before(v.Add_time) {
						gnss[k].Image = image.FileUrl
					}
				}

			} else {
				if image.AddTime.After(last) && image.AddTime.Before(v.Add_time) {
					gnss[k].Image = image.FileUrl
				}
			}
		}
		last = v.Add_time
		if gnss[k].Maxspeed <= 0 {
		} else {
			gnss[k].Maxspeed = gnss[k].Maxspeed / 10
		}
		if gnss[k].Velocitycar <= 0 {

		} else {
			gnss[k].Velocitycar = gnss[k].Velocitycar / 10
		}
		if gnss[k].Mileage <= 0 {

		} else {
			gnss[k].Mileage = utils.RoundFloat(float64(gnss[k].Mileage/10), 2)
		}
	}
	if len(file) >= 1 {
		if len(gnss) >= 1 {
			gnss[len(gnss)-1].Image = file[len(file)-1].FileUrl
		} else {
		}
	}
	for _, records := range gnss {
		var trailinfo trail
		trailinfo.ImageUrl = ""
		trailinfo.Latitude = records.Latitude
		trailinfo.Longitude = records.Longitude
		for _, image := range file {
			if image.AddTime.After(last) && image.AddTime.Before(records.Datetime) {
				trailinfo.ImageUrl = image.FileUrl
			}
		}
		last = records.Datetime
		trailList = append(trailList, trailinfo)
	}
	//获取学时详情照片
	headpic, _ := new(models.LearnRecord).GetPortrait(c.PostForm("id"))
	if strconv.FormatInt(record.CoachLoginId, 10) != "" {
		coachLoginLog, _ := new(models.CoachLoginlog).GetById(strconv.FormatInt(record.CoachLoginId, 10))
		coachLogin = coachLoginLog.Imglogin
		coachLogout = coachLoginLog.Imglogout
		coachLoginTime = coachLoginLog.Datetimelogin
		coachLogoutTime = coachLoginLog.Datetimelogout
	}
	record.CurHours = curHours
	record.CurMileage = cast.ToFloat32(utils.Decimal(cast.ToFloat64(curMileage), "2"))
	record.Zero = zero
	record.ZeroFive = zeroFive
	record.Five = five
	record.RenKeTime = renKeTime
	record.SubjectTotalHours = subjectTotalHours
	record.SubjectTotalMileage = subjectTotalMileage
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error(), "data": nil})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "获取培训过程明细", "data": map[string]interface{}{
		"Student_headpic": headpic.ImageUrl,
		"traillist":       trailList,
		"Coachlogin":      coachLogin,
		"Coachlogout":     coachLogout,
		"Coachlogintime":  coachLoginTime,
		"Coachlogouttime": coachLogoutTime,
		"record":          record,
		"file":            file,
		"gnss":            gnss,
	}})
	return
}

func StageList(c *gin.Context) {
	var (
		name     string
		phone    string
		idNumber string
		schoolId string
	)
	page, _ := strconv.Atoi(c.DefaultPostForm("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultPostForm("pageSize", "20"))
	offset := (page - 1) * pageSize
	filter := builder.NewCond()
	user, _ := common.GetCtxUser(c)
	if user.Type == "0" || user.Type == "1" {
		//管理用户查询全部
	} else {
		if user.Province != "" {
			filter = filter.And(builder.Eq{"s.province": user.Province})
		}
		if user.City != "" {
			filter = filter.And(builder.Eq{"s.city": user.City})
		}
		if user.District != "" {
			filter = filter.And(builder.Eq{"s.district": user.District})
		}
	}
	if user.Type == "3" {
		//同一个地区双代理
		filter = filter.And(builder.Eq{"s.config": user.SchoolList})
	}
	if schoolId = c.PostForm("school_id"); schoolId != "" {
		filter = filter.And(builder.Eq{"s.id": schoolId})
	}
	if name = c.PostForm("name"); name != "" {
		filter = filter.And(builder.Eq{"u.name": name})
	}
	if phone = c.PostForm("phone"); phone != "" {
		filter = filter.And(builder.Eq{"u.phone": phone})
	}
	if idNumber = c.PostForm("id_number"); idNumber != "" {
		filter = filter.And(builder.Eq{"u.id_number": idNumber})
	}
	filter = filter.And(builder.Eq{"u.type": "4"}).And(builder.Eq{"st.isused": "1"})
	list, count, _ := new(models.Task).GetTaskList(filter, pageSize, offset)
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "获取培训过程明细", "data": gin.H{"list": list, "count": count}})
	return
}

func StageReportList(c *gin.Context) {
	var (
		name     string
		phone    string
		idNumber string
		schoolId string
	)
	page, _ := strconv.Atoi(c.DefaultPostForm("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultPostForm("pageSize", "20"))
	offset := (page - 1) * pageSize
	filter := builder.NewCond()
	user, _ := common.GetCtxUser(c)
	if user.Type == "0" || user.Type == "1" {
		//管理用户查询全部
	} else {
		if user.Province != "" {
			filter = filter.And(builder.Eq{"s.province": user.Province})
		}
		if user.City != "" {
			filter = filter.And(builder.Eq{"s.city": user.City})
		}
		if user.District != "" {
			filter = filter.And(builder.Eq{"s.district": user.District})
		}
	}
	if user.Type == "3" {
		//同一个地区双代理
		filter = filter.And(builder.Eq{"s.config": user.SchoolList})
	}
	if schoolId = c.PostForm("school_id"); schoolId != "" {
		filter = filter.And(builder.Eq{"st.school_id": schoolId})
	}
	if name = c.PostForm("name"); name != "" {
		filter = filter.And(builder.Eq{"u.name": name})
	}
	if phone = c.PostForm("phone"); phone != "" {
		filter = filter.And(builder.Eq{"u.phone": phone})
	}
	if idNumber = c.PostForm("id_number"); idNumber != "" {
		filter = filter.And(builder.Eq{"u.id_number": idNumber})
	}
	filter = filter.And(builder.Eq{"u.type": "4"}).And(builder.Eq{"st.isused": "1"})
	list, count, _ := new(models.Reported).GetReportedList(filter, pageSize, offset)
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "成功", "data": gin.H{"list": list, "count": count}})
	return
}

func StageTraining(c *gin.Context) {
	var (
		reqUrl string
	)
	//获取参数
	valid := validation.Validation{}
	valid.Required(c.PostForm("school_id"), "school_id").Message("驾校id错误")
	valid.Required(c.PostForm("student_id"), "student_id").Message("学员id错误")
	valid.Required(c.PostForm("subject"), "subject").Message("科目获取失败")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}
	school, _ := new(models.School).GetSchool(c.PostForm("school_id"))
	if school.Id <= 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询失败", "data": nil})
		return
	}
	if c.PostForm("is_transfer") == "1" {
		reqUrl = BaeUrl + `/learnrecord/stage/training/record/single`
	} else {
		reqUrl = BaeUrl + `/learnrecord/stage/training/record`
	}
	data := url.Values{}
	data.Set("student_id", c.PostForm("student_id"))
	data.Set("school_id", cast.ToString(school.Id))
	data.Set("province", school.Province)
	data.Set("subject", c.PostForm("subject"))
	data.Set("city", school.City)
	data.Set("seal", c.PostForm("seal"))
	data.Set("institution_code", school.InstitutionCode)
	resp, err := utils.PostForm(reqUrl, data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error(), "data": nil})
		return
	}
	repMap, _ := cast.ToStringMapE(resp)
	repData, _ := cast.ToStringMapE(repMap["data"])
	c.JSON(http.StatusOK, gin.H{"code": cast.ToInt(repMap["code"]), "msg": cast.ToString(repMap["msg"]), "data": map[string]interface{}{"ids": repData["ids"], "outpdf": repData["outpdf"], "signdata": repData["signdata"], "province": school.Province, "city": school.City, "institution_code": school.InstitutionCode, "school_id": school.Id}})
	return

}

func StageSing(c *gin.Context) {
	//获取参数
	valid := validation.Validation{}
	valid.Required(c.PostForm("school_id"), "school_id").Message("驾校id错误")
	valid.Required(c.PostForm("pdf"), "pdf").Message("pdf文件错误")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}
	school, _ := new(models.School).GetSchool(c.PostForm("school_id"))
	if school.Id <= 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询失败", "data": nil})
		return
	}
	reqUrl := BaeUrl + `/learnrecord/sign/stage/record`
	log.Println(reqUrl, "~~~~~~~~~~~~~~~~")
	data := url.Values{}
	data.Set("sign", c.PostForm("sign"))
	data.Set("pdf", c.PostForm("pdf"))
	data.Set("ids", c.PostForm("ids"))
	data.Set("id", c.PostForm("id"))
	data.Set("province", school.Province)
	data.Set("city", school.City)
	data.Set("signdata", c.PostForm("signdata"))
	resp, err := utils.PostForm(reqUrl, data)
	log.Println(resp, "~~~~~~~~~~~~~~~~")
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error(), "data": nil})
		return
	}
	repMap, _ := cast.ToStringMapE(resp)
	c.JSON(http.StatusOK, gin.H{"code": cast.ToInt(repMap["code"]), "msg": cast.ToString(repMap["msg"]), "data": nil})
	return
}

func StageQuery(c *gin.Context) {
	var (
		reqUrl string
	)
	//获取参数
	valid := validation.Validation{}
	valid.Required(c.PostForm("school_id"), "school_id").Message("驾校id错误")
	valid.Required(c.PostForm("subject"), "subject").Message("科目获取失败")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}
	school, _ := new(models.School).GetSchool(c.PostForm("school_id"))
	if school.Id <= 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询失败", "data": nil})
		return
	}
	reqUrl = BaeUrl + `/learnrecord/admin/stage/record/review`
	data := url.Values{}
	data.Set("id", c.PostForm("id"))
	data.Set("province", school.Province)
	data.Set("city", school.City)
	data.Set("school_id", c.PostForm("school_id"))
	data.Set("subject", c.PostForm("subject"))
	log.Println(data)
	resp, err := utils.PostForm(reqUrl, data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error(), "data": nil})
		return
	}
	repMap, _ := cast.ToStringMapE(resp)
	log.Print(repMap)
	c.JSON(http.StatusOK, gin.H{"code": cast.ToInt(repMap["code"]), "msg": cast.ToString(repMap["msg"]), "data": nil})
	return
}

func StageDetail(c *gin.Context) {
	var (
		shiche    int
		moni      int
		ketang    int
		yuancheng int
		totalMin  int
		totalMil  float32
	)
	valid := validation.Validation{}
	valid.Required(c.PostForm("id"), "id").Message("id错误")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}
	has, list, _ := new(models.Task).GetById(c.PostForm("id"))
	if !has {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询失败", "data": nil})
		return
	}
	record, _ := new(models.LearnRecord).GetStudentAllRecord(list.StudentId, list.Subject)
	needReport, _ := new(models.LearnRecord).GetStudentNeedReport(list.StudentId, list.Subject)
	for _, v := range record {
		if v.Type == "1" {
			shiche += v.LastingMinute
		} else if v.Type == "2" {
			ketang += v.LastingMinute
		} else if v.Type == "3" {
			moni += v.LastingMinute
		} else if v.Type == "4" {
			yuancheng += v.LastingMinute
		}
		totalMin += v.LastingMinute
		totalMil += v.Mileage
	}
	list.Shicao = shiche
	list.Moni = moni
	list.Ketang = ketang
	list.Yuancheng = yuancheng
	list.Validetime = totalMin
	list.Validmileage = utils.Decimal(float64(totalMil/10), "2")
	list.NeedReportTime = needReport.LastingMinute
	list.NeedReportMileage = utils.Decimal(needReport.Mileage/10, "2")
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "成功", "data": gin.H{"list": list}})
	return
}

// ReMoveToTask 移回上报管理
func ReMoveToTask(c *gin.Context) {
	var (
		task models.Task
	)
	valid := validation.Validation{}
	valid.Required(c.PostForm("student_id"), "student_id").Message("学员id错误")
	valid.Required(c.PostForm("subject"), "subject").Message("科目错误")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Message, "data": nil})
			return
		}
	}
	has, list, _ := new(models.Reported).CheckExist(c.PostForm("student_id"), c.PostForm("subject"))
	if !has {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询失败", "data": nil})
		return
	}
	task.SchoolId = list.SchoolId
	task.StudentId = list.StudentId
	task.Subject = list.Subject
	task.Validetime = list.Validetime
	task.Validmileage = list.Validmileage
	task.Isreport = "0"
	task.Checktime = time.Now()
	task.UpdateTime = time.Now()
	task.Save()
	list.Delete()
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "成功", "data": nil})
	return
}

// ResetMinute 学时为0的，重置分钟数、公里数
func ResetMinute(c *gin.Context) {
	var (
		id string
	)
	id = c.PostForm("id")
	rhas, record, _ := new(models.LearnRecord).GetRecordById(id)
	if record.CoachId == 100 || (record.LastingMinute != 0 && record.Mileage != 0) {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "不在处理范围", "data": nil})
		return
	} else if !rhas {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	has, file, _ := new(models.File).GetFileByRecordId(record.Id)
	if !has {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "没有查询到登出记录", "data": nil})
		return
	}
	a, _ := time.Parse("2006-01-02 15:04:05", record.StartTime.Format("2006-01-02 15:04:05"))
	b, _ := time.Parse("2006-01-02 15:04:05", file.AddTime.Format("2006-01-02 15:04:05"))
	d := b.Sub(a)
	record.EndTime = file.AddTime
	if record.LastingMinute != 0 && record.Mileage == 0 {
		mileage, err := new(models.Gnss).GetByFilter(id)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "公里数计算错误", "data": nil})
			return
		}
		record.LastingMinute = cast.ToInt(math.Floor(d.Minutes()))
		record.Mileage = mileage
		record.Reason = ""
		record.Edit("end_time", "lasting_minute", "mileage", "reason")
	} else {
		record.Reason = ""
		record.LastingMinute = cast.ToInt(math.Floor(d.Minutes()))
		record.Edit("end_time", "lasting_minute", "reason")
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "成功", "data": nil})
	return
}

// ClearMinute 学时为0
func ClearMinute(c *gin.Context) {
	var (
		id string
	)
	id = c.PostForm("id")
	rhas, record, _ := new(models.LearnRecord).GetRecordById(id)
	if !rhas {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	record.LastingMinute = 0
	record.Mileage = 0
	record.Reason = "人工清空学时"
	record.Edit("reason", "lasting_minute", "mileage")
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "成功", "data": nil})
	return
}

func GetPdf(c *gin.Context) {
	var (
		pdfId    int
		has      bool
		portrait models.Upload
	)
	pdfId, _ = strconv.Atoi(c.PostForm("pdf_id"))
	if has, portrait, _ = new(models.Upload).GetPortraitById(int64(pdfId)); !has {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "获取PDF成功", "data": map[string]interface{}{"portrait": portrait.FileUrl}})
	return
}

func ClassRecord(c *gin.Context) {
	var (
		id string
	)
	id = c.PostForm("record_id")
	log.Println(id)
	if id == "" {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "参数错误", "data": nil})
		return
	}
	ok, record, err := new(models.LearnRecord).GetRecordById(id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "查询错误", "data": nil})
		return
	} else if !ok {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "记录不存在", "data": nil})
		return
	} else if record.LastingMinute <= 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "不足一分钟，无法备案", "data": nil})
		return
	}

}

// StageTrainTimeNewTest 阶段学时上报 山东省上报使用测试，不区分学员是否转入，统一使用改接口
func StageTrainTimeNewTest(c *gin.Context) {
	var (
		recarray       []map[string]string
		dayrecord      map[string]int
		classRoom      map[string]int
		classRoomCount int
		simulators     map[string]int
		simulatorCount int
		duration       int
		ids            []int
		mileage        float64
		sumtime        int
		totaltime      int
		networktime    int
		classtime      int
		vehicletime    int
		rectype        int
		list           []*models.SubjectLearn
		err            error
		subject1Time   int
		subject2Time   int
		subject4Time   int
	)
	schoolId, _ := strconv.Atoi(c.PostForm("school_id"))
	province := c.PostForm("province")
	subject := c.PostForm("subject")
	studentId, _ := strconv.Atoi(c.PostForm("student_id"))
	city := c.PostForm("city")
	student, err := new(models.Student).GetStudentUserById(studentId)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}

	if student.OperationStatus == "11" || student.OperationStatus == "12" || city == "370800" {
		list, err = new(models.LearnRecord).GetStudentAllLearnRecord(studentId)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}

	} else {
		list, err = new(models.LearnRecord).GetSubjectLearnRecord(studentId, subject)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
	}

	exam, err := new(models.Examiner).GetExaminerBySchoolId(schoolId, province)
	if exam.Id == 0 {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "未找到考核员"})
		return
	}
	dayrecord = make(map[string]int)

	recarray = make([]map[string]string, 0)
	classRoom = make(map[string]int)
	simulators = make(map[string]int)

	for _, v := range list {
		if v.Subject == subject || subject == "99" {
			sumtime += v.LastingMinute
			daystring := v.StartTime.Format("2006-01-02")
			dayrecord[daystring] += v.LastingMinute
			if dayrecord[daystring] >= 240 {
				dayrecord[daystring] = 240
			}
			if v.Isreport == "0" {
				duration += v.LastingMinute
			}
			if v.Subject == "1" {
				subject1Time += v.LastingMinute
			} else if v.Subject == "2" {
				subject2Time += v.LastingMinute
			} else if v.Subject == "4" {
				subject4Time += v.LastingMinute
			}
			ids = append(ids, v.Id)
			if v.Subject == "1" || v.Subject == "4" {
				recarray = append(recarray, map[string]string{"rnum": v.Sn})
				if v.Subject == "1" && province == "130000" && city == "130100" {
					if v.Type == "2" {
						classRoom[daystring] += v.LastingMinute
						if classRoom[daystring] > 180 {
							classRoom[daystring] = 180
						}
					}

				}

			} else {
				if province == "130000" && city == "130100" {
					if v.Type == "3" {
						simulators[daystring] += v.LastingMinute
						if simulators[daystring] > 180 {
							simulators[daystring] = 180
						}
						if student.OperationStatus == "11" || student.OperationStatus == "12" {
							recarray = append(recarray, map[string]string{"rnum": student.InstitutionCode + "9" + utils.Substr(v.Sn, -3, 4)})
						}

					}
				} else if province == "340000" {
					if v.Type == "3" {
						simulators[daystring] += v.LastingMinute
					}
				}
				if province != "510000" {
					if student.OperationStatus != "11" && student.OperationStatus != "12" {
						listGnss, err := new(models.Gnss).GetGnssByRecordId(v.Id)
						if err != nil {
							c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
							return
						}
						for _, v := range listGnss {
							if len(v.LearnrecordNumber) == 0 {
								continue
							}
							recarray = append(recarray, map[string]string{"rnum": v.LearnrecordNumber})
						}
					}
				}

			}

		}
		mileage += v.Mileage

	}
	for _, v := range dayrecord {
		totaltime += v
	}
	for _, v := range classRoom {
		classRoomCount += v
	}
	for _, v := range simulators {
		simulatorCount += v
	}
	carRecordSetting := utils.CarRecordSetting(province, student.TrainingCarType, student.OperationStatus, subject)
	if student.Istransfer == "1" {
		//转入学员不判断学时满足情况
	} else {
		if subject == "1" {
			if totaltime < carRecordSetting {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": fmt.Sprintf("有效学时至少达到%d学时,现计时平台有效学时为：%d学时%d分", carRecordSetting/45, totaltime/45, totaltime%45)})
				return
			}
		} else if subject == "2" {
			if totaltime < carRecordSetting {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": fmt.Sprintf("有效学时至少达到%d学时,现计时平台有效学时为：%d学时%d分", carRecordSetting/45, totaltime/45, totaltime%45)})
				return
			}
		} else if subject == "3" {
			if totaltime < carRecordSetting {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": fmt.Sprintf("有效学时至少达到%d学时,现计时平台有效学时为：%d学时%d分", carRecordSetting/45, totaltime/45, totaltime%45)})
				return
			}
			if mileage < 2600.0 {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": fmt.Sprintf("有效里程至少达到260公里,现计时平台有效学时为：%g公里", mileage/10)})
				return
			}
		} else if subject == "4" {
			if totaltime < carRecordSetting {
				c.JSON(http.StatusOK, gin.H{"code": 201, "msg": fmt.Sprintf("有效学时至少达到%d学时,现计时平台有效学时为：%d学时%d分", carRecordSetting/45, totaltime/45, totaltime%45)})
				return
			}
		}
	}

	if subject == "1" || subject == "4" {
		classtime = totaltime
		networktime = 0
		rectype = 2
		vehicletime = 0
	} else if subject == "2" || subject == "3" {
		classtime = 0
		networktime = 0
		rectype = 1
		vehicletime = totaltime
	} else {
		rectype = 5
	}
	log.Println(student.SchoolCode)
	data := map[string]interface{}{
		"inscode":       student.SchoolCode,
		"stunum":        student.InstitutionCode,
		"subject":       subject,
		"totaltime":     sumtime, //培训部分总学时
		"vehicletime":   vehicletime,
		"classtime":     classtime,
		"simulatortime": 0,
		"networktime":   networktime,
		"duration":      duration, //培训学时
		"examresult":    1,        //考核结果
		"mileage":       fmt.Sprintf("%.2f", mileage/10),
		"rectype":       rectype,
		"recarray":      recarray,
	}
	signData, err := json.Marshal(data)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	id_num := strings.Replace(student.IdNumber, "t", "", -1)
	pdfdata := make(map[string]string)
	if subject == "1" {
		pdfdata[student.TrainingCarType] = "https://oss.hahajishi.cn/static/duigou.jpg"
		pdfdata["name"] = student.Name
		pdfdata["sex"] = Sex[student.Sex]
		pdfdata["address"] = student.Address
		pdfdata["idcard"] = id_num
		pdfdata["photo"] = student.ImageUrl
		pdfdata["phone"] = student.Phone
		pdfdata["sdate"] = student.SignInTime.Format("2006-01-02")
		pdfdata["s1thrhours"] = fmt.Sprintf("%d学时%d分钟", totaltime/45, totaltime%45)
		pdfdata["institution_code"] = student.InstitutionCode
		//pdfdata["p1mil"] = "--"
		//pdfdata["s1result"] = "合格"
		pdfdata["stunum"] = student.InstitutionCode //学员编号
		pdfdata["signature1"] = "./static/admin/img/seal.png"
		//pdfdata["p1exam"] = exam.Name
		pdfdata["subject"] = "1"
		pdfdata["signyear1"] = fmt.Sprintf("%s    %s   %s", time.Now().Format("2006"), time.Now().Format("01"), time.Now().Format("02"))
	} else if subject == "2" {
		pdfdata["institution_code"] = student.InstitutionCode
		//pdfdata["p2mil"] = fmt.Sprintf("%.2f(km)", mileage/10)
		pdfdata["s2thrhours"] = fmt.Sprintf("%d学时%d分钟", totaltime/45, totaltime%45)
		//pdfdata["s2result"] = "合格"
		//pdfdata["p2exam"] = exam.Name
		pdfdata["subject"] = "2"
		pdfdata["signature2"] = "./static/admin/img/seal.png"
		pdfdata["signyear2"] = fmt.Sprintf("%s     %s   %s", time.Now().Format("2006"), time.Now().Format("01"), time.Now().Format("02"))
	} else if subject == "3" {
		pdfdata["institution_code"] = student.InstitutionCode
		pdfdata["s3thrhours"] = fmt.Sprintf("%d学时%d分钟", totaltime/45, totaltime%45)
		pdfdata["subject"] = "3"
		//pdfdata["p3mil"] = fmt.Sprintf("%.2fkm", mileage/10)
		//pdfdata["s3result"] = "合格"
		//pdfdata["p3exam"] = exam.Name
		pdfdata["signature3"] = "./static/admin/img/seal.png"
		pdfdata["signyear3"] = fmt.Sprintf("%s     %s    %s", time.Now().Format("2006"), time.Now().Format("01"), time.Now().Format("02"))

	} else {
		pdfdata["s4thrhours"] = fmt.Sprintf("%d学时%d分钟", totaltime/45, totaltime%45)
		pdfdata["institution_code"] = student.InstitutionCode
		//pdfdata["p4mil"] = "--"
		//pdfdata["s4result"] = "合格"
		pdfdata["subject"] = "4"
		//pdfdata["p4exam"] = exam.Name
		pdfdata["signature4"] = "./static/admin/img/seal.png"
		pdfdata["signyear4"] = fmt.Sprintf("%s     %s  %s", time.Now().Format("2006"), time.Now().Format("01"), time.Now().Format("02"))
	}
	var pdfurl string
	if subject == "1" {
		pdfurl = "http://oss.hahajishi.cn/graduation/new_stage.pdf"
	} else {
		//学员查询上个审核通过的科目
		recordFile, err := new(models.Reported).GetLastPdfFile(schoolId, studentId)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
		pdfurl = recordFile.FileUrl
	}
	if pdfurl == "" {
		pdfurl = "http://oss.hahajishi.cn/graduation/new_stage.pdf"

		pdfdata[student.TrainingCarType] = "https://oss.hahajishi.cn/static/duigou.jpg"
		pdfdata["name"] = student.Name
		pdfdata["sex"] = Sex[student.Sex]
		pdfdata["address"] = student.Address
		pdfdata["idcard"] = id_num
		pdfdata["photo"] = student.ImageUrl
		pdfdata["phone"] = student.Phone
		pdfdata["sdate"] = student.SignInTime.Format("2006-01-02")
		pdfdata["stunum"] = student.InstitutionCode //学员编号
	}
	if pdfdata["address"] == "" {
		pdfdata["address"] = " "
	}
	//log.Println(pdfdata)
	var outpdf string
	if province == "340000" || province == "370000" {
		if student.Zhangurl == "" {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": "请将驾校图片章发给我们客服人员"})
			return
		}
		newZhang := ""
		if strings.Contains(student.Zhangurl, "chrono") {
			s := strings.Split(student.Zhangurl, "sign")
			newZhang = "http://oss.hahajishi.cn/sign" + s[1]
		} else {
			newZhang = student.Zhangurl
		}
		resp, err := http.Get(newZhang)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
		defer resp.Body.Close()
		zhangdata, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
		sa := make([]string, 0)
		for _, v := range zhangdata {
			sa = append(sa, fmt.Sprintf("%02X", v))
		}
		seal := strings.Join(sa, "")
		outpdf, err = utils.CreateNewPdf(pdfurl, pdfdata, "r", seal)
		if err != nil { // 头像文件不存在使用 学时照片
			c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "succes", "data": map[string]interface{}{"ids": ids, "outpdf": outpdf, "signdata": signData}})
		return
	}
	seal := c.PostForm("seal")
	outpdf, err = utils.CreatePdf(pdfurl, pdfdata, "r", seal)
	if err != nil { // 头像文件不存在使用 学时照片
		c.JSON(http.StatusOK, gin.H{"code": 201, "msg": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "succes", "data": map[string]interface{}{"ids": ids, "outpdf": outpdf, "signdata": signData}})
	return
}
